package com.dmxh.realm;

import com.dmxh.api.AdminAPI;
import com.dmxh.api.SellerAPI;
import com.dmxh.pojo.TbAdmin;
import com.dmxh.pojo.TbSeller;
import com.dmxh.result.Result;
import com.dmxh.token.LoginUsernamePasswordToken;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

public class Realm extends AuthorizingRealm {

    @Autowired
    private AdminAPI adminAPI;
    @Autowired
    private SellerAPI sellerAPI;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //将token转换为usernamepasswordtoken对象
        LoginUsernamePasswordToken usernamePasswordToken = (LoginUsernamePasswordToken) token;
        if (usernamePasswordToken.getType() == "admin") {
            TbAdmin tbAdmin = adminAPI.queryByName(usernamePasswordToken.getUsername());
            if (tbAdmin == null) {
                return null;
            }
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(tbAdmin, tbAdmin.getPassword(), ByteSource.Util.bytes(tbAdmin.getSalt()), "AdminRealm");
            return simpleAuthenticationInfo;
        } else {
            TbSeller tbSeller = sellerAPI.queryByName(usernamePasswordToken.getUsername());
            if (tbSeller == null) {
                return null;
            }
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(tbSeller, tbSeller.getPassword(), ByteSource.Util.bytes(tbSeller.getSalt()), "SellerRealm");
            return simpleAuthenticationInfo;
        }


    }
}
